from datetime import datetime

from PyQt5.QtCore import Qt, QDate, QPoint
from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QPushButton, QTableWidget, QTableWidgetItem,
    QTabWidget, QMessageBox, QLineEdit, QDialog,
    QDialogButtonBox, QFormLayout, QComboBox, QDateEdit, QInputDialog, QTextEdit, QMenu
)


class RoleBasedDashboard(QMainWindow):
    def __init__(self, user_info, auth_manager, login_window):
        super().__init__()
        self.user_info = user_info
        self.auth_manager = auth_manager
        self.login_window = login_window
        self.init_ui()
        self.load_data()

    def show_empty_state(self):
        """显示空数据状态提示"""
        # 创建提示标签
        empty_label = QLabel("当前没有可用数据")
        empty_label.setAlignment(Qt.AlignCenter)
        empty_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                color: #666;
                padding: 20px;
            }
        """)
        # 清除当前数据容器内容
        if hasattr(self, 'data_container'):
            # 如果已经有专用数据容器
            for i in reversed(range(self.data_container.layout().count())):
                self.data_container.layout().itemAt(i).widget().setParent(None)
            self.data_container.layout().addWidget(empty_label)
        else:
            # 如果没有专用容器，直接显示在中央
            self.centralWidget().layout().addWidget(empty_label)

    def show_error_state(self, message="数据加载失败"):
        """显示错误状态提示"""
        error_label = QLabel(f"⚠️ {message}")
        error_label.setAlignment(Qt.AlignCenter)
        error_label.setStyleSheet("""
            QLabel {
                font-size: 16px;
                color: #d32f2f;
                padding: 20px;
            }
        """)
        if hasattr(self, 'data_container'):
            for i in reversed(range(self.data_container.layout().count())):
                self.data_container.layout().itemAt(i).widget().setParent(None)
            self.data_container.layout().addWidget(error_label)
        else:
            self.centralWidget().layout().addWidget(error_label)

    def load_data(self):
        """加载角色数据（兼容空数据库）"""
        try:
            # 获取数据
            data = self.auth_manager.get_role_dashboard_data(
                self.user_info['user_id'],
                self.user_info['role']
            )
            # 清除可能存在的旧状态提示
            self.clear_state_messages()
            # 根据角色加载界面
            if self.user_info['role'] == 'patient':
                self.load_patient_data(data or {})
            elif self.user_info['role'] == 'doctor':
                self.load_doctor_data(data or {})
            elif self.user_info['role'] == 'therapist':
                self.load_therapist_data(data or {})
            # 检查是否为空数据
            if self.is_data_empty(data):
                self.show_empty_state()
        except Exception as e:
            print(f"加载数据失败: {e}")
            self.show_error_state(f"数据加载失败: {str(e)}")

    def clear_state_messages(self):
        """清除状态消息"""
        if hasattr(self, 'data_container'):
            layout = self.data_container.layout()
            for i in reversed(range(layout.count())):
                widget = layout.itemAt(i).widget()
                if isinstance(widget, QLabel) and "状态" in widget.text():
                    widget.setParent(None)

    def is_data_empty(self, data):
        """检查数据是否为空"""
        if not data:
            return True
        return all(not v for v in data.values())

    def init_ui(self):
        """初始化界面基本结构"""
        self.setWindowTitle("康复训练管理系统")
        self.setMinimumSize(1200, 800)
        # 主控件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        # 主布局
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        # 顶部导航栏
        self.create_navbar(main_layout)
        # 选项卡区域
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        # 根据角色初始化不同界面
        self.init_role_specific_ui()

    def create_navbar(self, parent_layout):
        """创建顶部导航栏"""
        navbar = QHBoxLayout()
        # 角色中文字典映射
        role_names = {
            'doctor': '医生',
            'therapist': '治疗师',
            'patient': '患者'
        }
        welcome_label = QLabel(
            f"欢迎回来，{role_names.get(self.user_info['role'], self.user_info['role'])} {self.user_info['username']}！"
        )
        welcome_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        logout_btn = QPushButton("退出")
        logout_btn.setFixedWidth(100)
        logout_btn.clicked.connect(self.logout)
        navbar.addWidget(welcome_label)
        navbar.addStretch()
        navbar.addWidget(logout_btn)
        parent_layout.addLayout(navbar)

    def init_role_specific_ui(self):
        """根据用户角色初始化对应界面"""
        if self.user_info['role'] == 'doctor':
            self.init_doctor_ui()
        elif self.user_info['role'] == 'therapist':
            self.init_therapist_ui()
        elif self.user_info['role'] == 'patient':
            self.init_patient_ui()

    def init_doctor_ui(self):
        """医生专属界面"""
        # 治疗师管理标签页
        therapist_tab = QWidget()
        therapist_layout = QVBoxLayout()
        self.therapists_table = QTableWidget()
        self.therapists_table.setColumnCount(3)  # 将列数设置为3
        self.therapists_table.setHorizontalHeaderLabels([
            '治疗师ID', '姓名', '负责患者数'
        ])
        self.therapists_table.setSelectionBehavior(QTableWidget.SelectRows)
        # 分配治疗师按钮
        assign_therapist_btn = QPushButton("分配治疗师")
        assign_therapist_btn.clicked.connect(self.assign_therapist_to_doctor)
        therapist_layout.addWidget(QLabel("管理的治疗师团队:"))
        therapist_layout.addWidget(self.therapists_table)
        therapist_layout.addWidget(assign_therapist_btn)
        therapist_tab.setLayout(therapist_layout)
        self.tab_widget.addTab(therapist_tab, "治疗师管理")
        # 患者管理标签页
        patient_tab = QWidget()
        patient_layout = QVBoxLayout()
        self.patients_table = QTableWidget()
        self.patients_table.setColumnCount(5)
        self.patients_table.setHorizontalHeaderLabels([
            '患者ID', '姓名', '性别', '年龄', '负责治疗师'
        ])
        self.patients_table.setSelectionBehavior(QTableWidget.SelectRows)
        # 新增患者按钮
        add_patient_btn = QPushButton("新增患者")
        add_patient_btn.clicked.connect(self.show_add_patient_dialog)
        patient_layout.addWidget(QLabel("治疗师团队的患者概览:"))
        patient_layout.addWidget(self.patients_table)
        patient_layout.addWidget(add_patient_btn)
        patient_tab.setLayout(patient_layout)
        self.tab_widget.addTab(patient_tab, "患者管理")

    def load_doctor_data(self, data):
        """加载医生数据"""
        try:
            # 加载治疗师数据
            therapists = data.get('therapists', [])
            self.therapists_table.setRowCount(len(therapists))
            for row, therapist in enumerate(therapists):
                self.therapists_table.setItem(row, 0, QTableWidgetItem(str(therapist['therapist_id'])))
                self.therapists_table.setItem(row, 1, QTableWidgetItem(therapist['username']))
                self.therapists_table.setItem(row, 2, QTableWidgetItem(str(therapist['patient_count'])))
            # 加载患者数据
            patients = data.get('patients', [])
            self.patients_table.setRowCount(len(patients))
            for row, patient in enumerate(patients):
                age = datetime.now().year - patient['birth_date'].year if patient.get('birth_date') else '未知'
                self.patients_table.setItem(row, 0, QTableWidgetItem(str(patient['patient_id'])))
                self.patients_table.setItem(row, 1, QTableWidgetItem(patient['name']))
                self.patients_table.setItem(row, 2, QTableWidgetItem(patient.get('gender', '未知')))
                self.patients_table.setItem(row, 3, QTableWidgetItem(str(age)))
                self.patients_table.setItem(row, 4, QTableWidgetItem(patient.get('therapist_name', '未分配')))
            # 设置表格自适应
            self.therapists_table.resizeColumnsToContents()
            self.patients_table.resizeColumnsToContents()
        except Exception as e:
            QMessageBox.warning(self, "加载失败", f"加载数据时出错: {str(e)}")

    def show_add_patient_dialog(self):
        """显示添加患者对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle("新增患者")
        dialog.setFixedSize(400, 300)
        layout = QFormLayout(dialog)
        # 表单字段
        name_edit = QLineEdit()
        gender_combo = QComboBox()
        gender_combo.addItems(["男", "女", "其他"])
        birth_date_edit = QDateEdit()
        birth_date_edit.setCalendarPopup(True)
        birth_date_edit.setDate(QDate.currentDate().addYears(-30))
        phone_edit = QLineEdit()
        address_edit = QTextEdit()
        address_edit.setFixedHeight(60)
        # 获取可分配的治疗师列表
        therapist_combo = QComboBox()
        therapist_combo.addItem("未分配", None)
        for i in range(self.therapists_table.rowCount()):
            therapist_id = self.therapists_table.item(i, 0).text()
            therapist_name = self.therapists_table.item(i, 1).text()
            therapist_combo.addItem(f"{therapist_name} (ID: {therapist_id})")
        # 按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        # 添加控件到布局
        layout.addRow("姓名:", name_edit)
        layout.addRow("性别:", gender_combo)
        layout.addRow("出生日期:", birth_date_edit)
        layout.addRow("联系电话:", phone_edit)
        layout.addRow("地址:", address_edit)
        layout.addRow("负责治疗师:", therapist_combo)
        layout.addRow(btn_box)
        if dialog.exec_() == QDialog.Accepted:
            # 收集数据并保存
            patient_data = {
                'name': name_edit.text(),
                'gender': gender_combo.currentText(),
                'birth_date': birth_date_edit.date().toString("yyyy-MM-dd"),
                'phone': phone_edit.text(),
                'address': address_edit.toPlainText(),
                'therapist_id': therapist_combo.currentData()
            }
            self.save_new_patient(patient_data)

    def show_edit_patient_dialog(self):
        """显示编辑患者对话框"""
        selected_rows = self.patients_table.selectionModel().selectedRows()
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先选择要编辑的患者")
            return

        row = selected_rows[0].row()
        patient_id = self.patients_table.item(row, 0).text()
        # 获取当前患者数据
        current_data = {
            'name': self.patients_table.item(row, 1).text(),
            'gender': self.patients_table.item(row, 2).text(),
            'age': self.patients_table.item(row, 3).text(),
            'therapist': self.patients_table.item(row, 4).text()
        }
        dialog = QDialog(self)
        dialog.setWindowTitle("编辑患者信息")
        dialog.setFixedSize(400, 300)
        layout = QFormLayout(dialog)
        # 表单字段
        name_edit = QLineEdit(current_data['name'])
        gender_combo = QComboBox()
        gender_combo.addItems(["男", "女", "其他"])
        gender_combo.setCurrentText(current_data['gender'])
        # 计算出生日期
        current_year = datetime.now().year
        birth_year = current_year - int(current_data['age']) if current_data['age'].isdigit() else current_year - 30
        birth_date_edit = QDateEdit(QDate(birth_year, 1, 1))
        birth_date_edit.setCalendarPopup(True)
        # 治疗师选择
        therapist_combo = QComboBox()
        therapist_combo.addItem("未分配", None)
        current_therapist = current_data['therapist']
        current_therapist_index = 0
        for i in range(self.therapists_table.rowCount()):
            therapist_id = self.therapists_table.item(i, 0).text()
            therapist_name = self.therapists_table.item(i, 1).text()
            display_text = f"{therapist_name} (ID: {therapist_id})"
            therapist_combo.addItem(display_text, therapist_id)
            if therapist_name == current_therapist:
                current_therapist_index = i + 1  # +1 因为有"未分配"选项
        therapist_combo.setCurrentIndex(current_therapist_index)
        # 按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        # 添加控件到布局
        layout.addRow("姓名:", name_edit)
        layout.addRow("性别:", gender_combo)
        layout.addRow("出生日期:", birth_date_edit)
        layout.addRow("负责治疗师:", therapist_combo)
        layout.addRow(btn_box)

        if dialog.exec_() == QDialog.Accepted:
            # 收集数据并保存
            updated_data = {
                'patient_id': patient_id,
                'name': name_edit.text(),
                'gender': gender_combo.currentText(),
                'birth_date': birth_date_edit.date().toString("yyyy-MM-dd"),
                'therapist_id': therapist_combo.currentData()
            }
            self.update_patient(updated_data)

    def show_patient_actions(self, row):
        """显示患者操作菜单"""
        menu = QMenu(self)
        view_action = menu.addAction("查看详情")
        edit_action = menu.addAction("编辑信息")
        assign_action = menu.addAction("分配治疗师")
        delete_action = menu.addAction("删除患者")
        # 获取点击位置
        button = self.patients_table.cellWidget(row, 5)
        pos = button.mapToGlobal(QPoint(0, button.height()))
        action = menu.exec_(pos)
        if action == view_action:
            self.view_patient_details(row)
        elif action == edit_action:
            self.show_edit_patient_dialog()
        elif action == assign_action:
            self.assign_therapist_to_patient(row)
        elif action == delete_action:
            self.delete_patient()

    def assign_therapist_to_patient(self, row):
        """为患者分配治疗师"""
        patient_id = self.patients_table.item(row, 0).text()
        patient_name = self.patients_table.item(row, 1).text()
        dialog = QDialog(self)
        dialog.setWindowTitle(f"为 {patient_name} 分配治疗师")
        dialog.setFixedSize(300, 150)
        layout = QVBoxLayout(dialog)
        therapist_combo = QComboBox()
        therapist_combo.addItem("未分配", None)
        for i in range(self.therapists_table.rowCount()):
            therapist_id = self.therapists_table.item(i, 0).text()
            therapist_name = self.therapists_table.item(i, 1).text()
            therapist_combo.addItem(f"{therapist_name} (ID: {therapist_id})", therapist_id)
        # 设置当前治疗师
        current_therapist = self.patients_table.item(row, 4).text()
        current_index = 0
        for i in range(therapist_combo.count()):
            if current_therapist in therapist_combo.itemText(i):
                current_index = i
                break
        therapist_combo.setCurrentIndex(current_index)
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        layout.addWidget(QLabel("选择治疗师:"))
        layout.addWidget(therapist_combo)
        layout.addWidget(btn_box)
        if dialog.exec_() == QDialog.Accepted:
            therapist_id = therapist_combo.currentData()
            try:
                # 这里调用API分配治疗师
                # response = self.api_client.assign_therapist_to_patient(patient_id, therapist_id)
                # 模拟成功响应
                QMessageBox.information(self, "成功", "治疗师分配成功")
                self.load_data()  # 刷新数据
            except Exception as e:
                QMessageBox.warning(self, "错误", f"分配治疗师失败: {str(e)}")


    def assign_therapist_to_doctor(self):
        """为医生团队分配治疗师"""
        available_therapists = self.auth_manager.get_available_therapists(self.user_info['user_id'])
        if not available_therapists:
            QMessageBox.information(self, "提示", "没有可分配的治疗师")
            return
        therapist_names = [t['username'] for t in available_therapists]
        therapist_name, ok = QInputDialog.getItem(
            self, "分配治疗师",
            "选择要添加到团队的治疗师:",
            therapist_names, 0, False
        )
        if ok and therapist_name:
            therapist_id = next(t['user_id'] for t in available_therapists if t['username'] == therapist_name)
            try:
                success = self.auth_manager.assign_therapist_to_doctor(
                    doctor_id=self.user_info['user_id'],
                    therapist_id=therapist_id
                )
                if success:
                    QMessageBox.information(self, "成功", "治疗师分配成功")
                    self.load_data()  # 刷新数据
                else:
                    QMessageBox.warning(self, "失败", "治疗师分配失败")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"分配时出错: {str(e)}")

    def view_therapist_patients(self):
        """查看治疗师负责的患者"""
        selected = self.therapists_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择治疗师")
            return
        therapist_id = self.therapists_table.item(selected, 0).text()
        therapist_name = self.therapists_table.item(selected, 1).text()
        # 获取该治疗师的患者列表 (需要实现get_therapist_patients方法)
        try:
            patients = self.auth_manager.get_therapist_patients(therapist_id)
            dialog = QDialog(self)
            dialog.setWindowTitle(f"{therapist_name}负责的患者")
            layout = QVBoxLayout()
            table = QTableWidget()
            table.setColumnCount(4)
            table.setHorizontalHeaderLabels(['患者ID', '姓名', '性别', '年龄'])
            table.setRowCount(len(patients))
            for row, patient in enumerate(patients):
                age = datetime.now().year - patient['birth_date'].year if patient.get('birth_date') else '未知'
                table.setItem(row, 0, QTableWidgetItem(str(patient['patient_id'])))
                table.setItem(row, 1, QTableWidgetItem(patient['name']))
                table.setItem(row, 2, QTableWidgetItem(patient.get('gender', '未知')))
                table.setItem(row, 3, QTableWidgetItem(str(age)))
            layout.addWidget(table)
            dialog.setLayout(layout)
            dialog.exec_()
        except Exception as e:
            QMessageBox.warning(self, "加载失败", f"获取患者列表失败: {str(e)}")

    # 以下是简化版的管理方法实现
    def show_add_patient(self):
        """显示添加患者表单"""
        form = QDialog(self)
        form.setWindowTitle("添加新患者")
        layout = QFormLayout(form)
        # 表单字段
        name_edit = QLineEdit()
        gender_combo = QComboBox()
        gender_combo.addItems(["男", "女", "其他"])
        birth_edit = QDateEdit()
        birth_edit.setCalendarPopup(True)
        condition_edit = QLineEdit()
        # 添加到布局
        layout.addRow("姓名:", name_edit)
        layout.addRow("性别:", gender_combo)
        layout.addRow("出生日期:", birth_edit)
        layout.addRow("当前状况:", condition_edit)
        # 按钮
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(form.accept)
        buttons.rejected.connect(form.reject)
        layout.addRow(buttons)
        if form.exec_() == QDialog.Accepted:
            # 这里添加保存逻辑
            QMessageBox.information(self, "成功", "患者添加成功")

    def show_edit_patient(self):
        """显示编辑患者表单"""
        selected = self.patients_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择要编辑的患者")
            return
        patient_id = self.patients_table.item(selected, 0).text()
        # 这里添加获取患者详情的逻辑
        form = QDialog(self)
        form.setWindowTitle("编辑患者信息")
        layout = QFormLayout(form)
        # 表单字段(示例)
        name_edit = QLineEdit("示例患者名")
        gender_combo = QComboBox()
        gender_combo.addItems(["男", "女", "其他"])
        condition_edit = QLineEdit("示例状况")
        layout.addRow("姓名:", name_edit)
        layout.addRow("性别:", gender_combo)
        layout.addRow("当前状况:", condition_edit)
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(form.accept)
        buttons.rejected.connect(form.reject)
        layout.addRow(buttons)
        if form.exec_() == QDialog.Accepted:
            QMessageBox.information(self, "成功", "患者信息更新成功")

    def delete_patient(self):
        """删除患者"""
        selected = self.patients_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择要删除的患者")
            return
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除选中的患者吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            patient_id = self.patients_table.item(selected, 0).text()
            # 这里添加删除逻辑
            QMessageBox.information(self, "成功", "患者删除成功")

    def assign_therapist(self):
        """分配治疗师"""
        selected = self.patients_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择患者")
            return
        # 简单实现 - 实际应该从数据库获取治疗师列表
        therapist, ok = QInputDialog.getItem(
            self, "分配治疗师",
            "选择治疗师:",
            ["治疗师1", "治疗师2", "治疗师3"],
            0, False
        )
        if ok and therapist:
            patient_id = self.patients_table.item(selected, 0).text()
            # 这里添加分配逻辑
            QMessageBox.information(self, "成功", f"已为患者分配治疗师: {therapist}")

    def show_add_therapist(self):
        """添加治疗师关联"""
        # 简单实现 - 实际应该从数据库获取可添加的治疗师列表
        therapist, ok = QInputDialog.getItem(
            self, "添加治疗师",
            "选择要关联的治疗师:",
            ["治疗师A", "治疗师B", "治疗师C"],
            0, False
        )
        if ok and therapist:
            # 这里添加关联逻辑
            QMessageBox.information(self, "成功", f"已添加治疗师: {therapist}")

    def show_edit_therapist(self):
        """编辑治疗师信息"""
        selected = self.therapists_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择要编辑的治疗师")
            return
        therapist_id = self.therapists_table.item(selected, 0).text()
        # 这里添加获取治疗师详情的逻辑
        # 简单编辑示例
        new_name, ok = QInputDialog.getText(
            self, "编辑治疗师",
            "输入新用户名:",
            QLineEdit.Normal,
            self.therapists_table.item(selected, 1).text()
        )
        if ok and new_name:
            # 这里添加更新逻辑
            QMessageBox.information(self, "成功", "治疗师信息已更新")

    def remove_therapist(self):
        """移除治疗师关联"""
        selected = self.therapists_table.currentRow()
        if selected < 0:
            QMessageBox.warning(self, "警告", "请先选择要移除的治疗师")
            return
        reply = QMessageBox.question(
            self, "确认移除",
            "确定要移除选中的治疗师关联吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            therapist_id = self.therapists_table.item(selected, 0).text()
            # 这里添加移除逻辑
            QMessageBox.information(self, "成功", "治疗师关联已移除")

    def init_therapist_ui(self):
        """治疗师专属界面"""
        # 设备管理标签页
        devices_tab = QWidget()
        devices_layout = QVBoxLayout()
        self.devices_table = QTableWidget()
        self.devices_table.setColumnCount(6)
        self.devices_table.setHorizontalHeaderLabels([
            '设备ID', '类型', '状态', '位置', '最后校准', '操作'
        ])
        self.devices_table.setSelectionBehavior(QTableWidget.SelectRows)
        # 添加设备按钮
        add_device_btn = QPushButton("添加新设备")
        add_device_btn.clicked.connect(self.show_add_device_dialog)
        devices_layout.addWidget(QLabel("管理的医疗设备:"))
        devices_layout.addWidget(self.devices_table)
        devices_layout.addWidget(add_device_btn)
        devices_tab.setLayout(devices_layout)
        self.tab_widget.addTab(devices_tab, "设备管理")
        # 康复计划标签页
        plans_tab = QWidget()
        plans_layout = QVBoxLayout()
        self.plans_table = QTableWidget()
        self.plans_table.setColumnCount(7)  # 增加操作列
        self.plans_table.setHorizontalHeaderLabels([
            '计划ID', '患者姓名', '计划名称', '开始日期', '结束日期', '状态', '操作'
        ])
        self.plans_table.setSelectionBehavior(QTableWidget.SelectRows)
        # 添加计划按钮
        add_plan_btn = QPushButton("添加新计划")
        add_plan_btn.clicked.connect(self.show_add_plan_dialog)
        plans_layout.addWidget(QLabel("负责的康复计划:"))
        plans_layout.addWidget(self.plans_table)
        plans_layout.addWidget(add_plan_btn)
        plans_tab.setLayout(plans_layout)
        self.tab_widget.addTab(plans_tab, "康复计划")

    def init_patient_ui(self):
        """患者专属界面"""
        # 康复计划标签页
        plans_tab = QWidget()
        plans_layout = QVBoxLayout()
        self.plans_table = QTableWidget()
        self.plans_table.setColumnCount(5)
        self.plans_table.setHorizontalHeaderLabels([
            '计划ID', '计划名称', '治疗师', '开始日期', '进度'
        ])
        plans_layout.addWidget(QLabel("我的康复计划:"))
        plans_layout.addWidget(self.plans_table)
        plans_tab.setLayout(plans_layout)
        self.tab_widget.addTab(plans_tab, "康复计划")
        # 训练反馈标签页
        feedback_tab = QWidget()
        feedback_layout = QVBoxLayout()
        self.feedback_table = QTableWidget()
        self.feedback_table.setColumnCount(4)
        self.feedback_table.setHorizontalHeaderLabels([
            '训练日期', '训练项目', '疼痛等级', '完成率'
        ])
        feedback_layout.addWidget(QLabel("最近的训练反馈:"))
        feedback_layout.addWidget(self.feedback_table)
        feedback_tab.setLayout(feedback_layout)
        self.tab_widget.addTab(feedback_tab, "训练记录")

    def load_patient_data(self, data):
        """加载患者特定的数据"""
        try:
            print(data)  # 调试用，查看实际数据结构
            # 使用正确的字段名获取数据
            plans_data = data.get('active_plans', [])  # 改为active_plans
            self.plans_table.setRowCount(len(plans_data))
            for row, plan in enumerate(plans_data):
                self.plans_table.setItem(row, 0, QTableWidgetItem(str(plan.get('plan_id', ''))))
                self.plans_table.setItem(row, 1, QTableWidgetItem(plan.get('plan_name', '')))
                # 如果没有therapist_name字段，显示"未知治疗师"
                therapist_name = plan.get('therapist_name', '未知治疗师')
                self.plans_table.setItem(row, 2, QTableWidgetItem(therapist_name))
                # 处理日期格式
                start_date = plan.get('start_date', '')
                display_date = start_date.strftime("%Y-%m-%d") if hasattr(start_date, 'strftime') else str(start_date)
                self.plans_table.setItem(row, 3, QTableWidgetItem(display_date))
                # 状态显示
                status_mapping = {'active': '进行中', 'completed': '已完成', 'paused': '已暂停'}
                status = status_mapping.get(plan.get('status', 'active'), '进行中')
                self.plans_table.setItem(row, 4, QTableWidgetItem(status))
            feedback_data = data.get('latest_feedback', [])
            self.feedback_table.setRowCount(len(feedback_data))
            for row, feedback in enumerate(feedback_data):
                session_date = feedback.get('session_date', '')
                if hasattr(session_date, 'strftime'):
                    session_date = session_date.strftime("%Y-%m-%d")
                self.feedback_table.setItem(row, 0, QTableWidgetItem(str(session_date)))
                self.feedback_table.setItem(row, 1, QTableWidgetItem(feedback.get('exercise_name', '')))
                self.feedback_table.setItem(row, 2, QTableWidgetItem(str(feedback.get('pain_level', 0))))
                self.feedback_table.setItem(row, 3, QTableWidgetItem(f"{feedback.get('completion_rate', 0)}%"))
        except Exception as e:
            QMessageBox.warning(self, "加载失败", f"加载数据时出错: {str(e)}")

    def load_therapist_data(self, data):
        """加载治疗师数据"""
        # 设备数据
        self.devices_table.setRowCount(len(data['devices']))
        for row, device in enumerate(data['devices']):
            self.devices_table.setItem(row, 0, QTableWidgetItem(device['device_id']))
            self.devices_table.setItem(row, 1, QTableWidgetItem(device['device_type']))
            self.devices_table.setItem(row, 2, QTableWidgetItem(device['status']))
            self.devices_table.setItem(row, 3, QTableWidgetItem(device['location']))
            self.devices_table.setItem(row, 4, QTableWidgetItem(
                device['last_calibration'].strftime('%Y-%m-%d') if device['last_calibration'] else "N/A"
            ))
            # 操作按钮容器
            btn_container = QWidget()
            btn_layout = QHBoxLayout()
            btn_container.setLayout(btn_layout)
            # 编辑按钮
            edit_btn = QPushButton("编辑")
            edit_btn.setStyleSheet("padding: 2px 5px;")
            edit_btn.clicked.connect(lambda _, d=device: self.edit_device(d))
            # 删除按钮
            delete_btn = QPushButton("删除")
            delete_btn.setStyleSheet("padding: 2px 5px; color: red;")
            delete_btn.clicked.connect(lambda _, d=device: self.confirm_delete_device(d['device_id']))
            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.setContentsMargins(0, 0, 0, 0)
            self.devices_table.setCellWidget(row, 5, btn_container)
        # 康复计划数据
        self.plans_table.setRowCount(len(data['active_plans']))
        for row, plan in enumerate(data['active_plans']):
            self.plans_table.setItem(row, 0, QTableWidgetItem(str(plan['plan_id'])))
            self.plans_table.setItem(row, 1, QTableWidgetItem(plan['patient_name']))
            self.plans_table.setItem(row, 2, QTableWidgetItem(plan['plan_name']))
            self.plans_table.setItem(row, 3, QTableWidgetItem(
                plan['start_date'].strftime('%Y-%m-%d') if plan['start_date'] else "N/A"
            ))
            self.plans_table.setItem(row, 4, QTableWidgetItem(
                plan['end_date'].strftime('%Y-%m-%d') if plan['end_date'] else "N/A"
            ))
            self.plans_table.setItem(row, 5, QTableWidgetItem(plan['status']))
            # 操作按钮
            btn_container = QWidget()
            btn_layout = QHBoxLayout()
            btn_container.setLayout(btn_layout)
            edit_btn = QPushButton("编辑")
            edit_btn.setStyleSheet("padding: 2px 5px;")
            edit_btn.clicked.connect(lambda _, p=plan: self.edit_plan(p))
            delete_btn = QPushButton("删除")
            delete_btn.setStyleSheet("padding: 2px 5px; color: red;")
            delete_btn.clicked.connect(lambda _, pid=plan['plan_id']: self.confirm_delete_plan(pid))
            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)
            btn_layout.setContentsMargins(0, 0, 0, 0)
            self.plans_table.setCellWidget(row, 6, btn_container)

    def confirm_delete_device(self, device_id):
        """确认删除设备对话框"""
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要永久删除设备 {device_id} 吗？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            try:
                success, message = self.auth_manager.delete_device(
                    self.user_info['user_id'],
                    device_id
                )
                if success:
                    QMessageBox.information(self, "成功", message)
                    self.load_data()  # 刷新设备列表
                else:
                    QMessageBox.warning(self, "失败", message)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除设备失败: {str(e)}")

    def edit_device(self, device):
        """编辑设备信息对话框（基于枚举字典）"""
        dialog = QDialog(self)
        dialog.setWindowTitle(f"编辑设备 {device['device_id']}")
        # 定义枚举映射字典（与添加设备一致）
        STATUS_MAPPING = {
            "可用": "available",
            "维修中": "maintenance",
            "使用中": "in_use"
        }
        # 反向映射字典（英文->中文）
        REVERSE_STATUS_MAPPING = {v: k for k, v in STATUS_MAPPING.items()}
        layout = QFormLayout()
        # 使用下拉框替代文本输入框
        status_combo = QComboBox()
        status_combo.addItems(STATUS_MAPPING.keys())  # 添加中文选项
        # 设置当前选中项（将数据库中的英文值转换为中文显示）
        current_status = device['status']
        if current_status in REVERSE_STATUS_MAPPING:
            index = status_combo.findText(REVERSE_STATUS_MAPPING[current_status])
            if index >= 0:
                status_combo.setCurrentIndex(index)
        location_input = QLineEdit(device['location'])
        layout.addRow("状态:", status_combo)
        layout.addRow("位置:", location_input)
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addRow(buttons)
        dialog.setLayout(layout)
        if dialog.exec_() == QDialog.Accepted:
            # 获取用户选择的中文状态并转换为英文值
            selected_status_text = status_combo.currentText()
            new_status = STATUS_MAPPING.get(selected_status_text, device['status'])  # 默认保持原值
            new_location = location_input.text()
            try:
                success, message = self.auth_manager.edit_device(
                    self.user_info['user_id'],
                    device['device_id'],
                    new_status,  # 传递英文值
                    new_location
                )
                if success:
                    QMessageBox.information(self, "成功", message)
                    self.load_data()  # 刷新数据
                else:
                    QMessageBox.warning(self, "警告", message)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"设备更新失败: {str(e)}")

    def show_add_device_dialog(self):
        # 定义枚举映射字典（中文:英文）
        DEVICE_TYPE_MAPPING = {
            "康复仪": "motion_capture",
            "电疗机": "electrostimulator",
            "监测设备": "smart_brace"
        }
        STATUS_MAPPING = {
            "可用": "available",
            "维修中": "maintenance",
            "使用中": "in_use"
        }
        dialog = QDialog(self)
        dialog.setWindowTitle("添加设备")
        layout = QFormLayout(dialog)
        # 添加输入字段
        self.device_id_input = QLineEdit()
        self.device_type_combo = QComboBox()
        self.device_type_combo.addItems(DEVICE_TYPE_MAPPING.keys())  # 添加中文选项
        self.status_combo = QComboBox()
        self.status_combo.addItems(STATUS_MAPPING.keys())  # 添加中文选项
        self.location_input = QLineEdit()
        self.calibration_input = QDateEdit()
        self.calibration_input.setCalendarPopup(True)
        self.calibration_input.setDate(QDate.currentDate())
        layout.addRow("设备ID:", self.device_id_input)
        layout.addRow("设备类型:", self.device_type_combo)
        layout.addRow("状态:", self.status_combo)
        layout.addRow("位置:", self.location_input)
        layout.addRow("最后校准日期:", self.calibration_input)
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addRow(buttons)
        if dialog.exec_() == QDialog.Accepted:
            # 获取用户选择的中文文本并转换为英文值
            selected_device_type = self.device_type_combo.currentText()
            selected_status = self.status_combo.currentText()
            device_data = {
                'device_id': self.device_id_input.text(),
                'device_type': DEVICE_TYPE_MAPPING[selected_device_type],  # 存储英文值
                'status': STATUS_MAPPING[selected_status],  # 存储英文值
                'location': self.location_input.text(),
                'last_calibration': self.calibration_input.date().toString("yyyy-MM-dd")
            }
            # 验证必填字段
            if not all(device_data.values()):
                QMessageBox.warning(self, "错误", "所有字段必须填写")
                return
            success, message = self.auth_manager.add_new_device(
                therapist_id=self.user_info['user_id'],
                device_data=device_data
            )
            # 直接根据success显示结果
            if success:
                QMessageBox.information(self, "成功", message)
                self.load_data()  # 刷新设备列表
            else:
                QMessageBox.warning(self, "失败", message)

    def show_add_plan_dialog(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("添加康复计划")
        layout = QFormLayout(dialog)
        # 患者选择
        patient_combo = QComboBox()
        patients = self.auth_manager.get_patient_list(self.user_info['user_id'])
        for patient in patients:
            patient_combo.addItem(f"{patient['name']} (ID: {patient['id']})", patient['id'])
        # 计划信息输入
        plan_name = QLineEdit()
        start_date = QDateEdit()
        start_date.setDate(QDate.currentDate())
        end_date = QDateEdit()
        end_date.setDate(QDate.currentDate().addMonths(1))
        frequency = QComboBox()
        frequency.addItems(['每日', '每周', '每两周'])
        status = QComboBox()
        status.addItems(['进行中', '已完成', '已暂停'])
        # 添加控件
        layout.addRow("患者:", patient_combo)
        layout.addRow("计划名称:", plan_name)
        layout.addRow("开始日期:", start_date)
        layout.addRow("结束日期:", end_date)
        layout.addRow("频率:", frequency)
        layout.addRow("状态:", status)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addRow(buttons)

        if dialog.exec_() == QDialog.Accepted:
            plan_data = {
                'patient_id': patient_combo.currentData(),
                'therapist_id': self.user_info['user_id'],
                'plan_name': plan_name.text(),
                'start_date': start_date.date().toString("yyyy-MM-dd"),
                'end_date': end_date.date().toString("yyyy-MM-dd"),
                'frequency': ['daily', 'weekly', 'biweekly'][frequency.currentIndex()],
                'status': ['active', 'completed', 'paused'][status.currentIndex()]
            }
            success, result = self.auth_manager.add_rehab_plan(plan_data)
            if success:
                QMessageBox.information(self, "成功", f"计划创建成功，ID: {result}")
            else:
                QMessageBox.warning(self, "错误", result)

    def edit_plan(self, plan):
        """编辑康复计划对话框"""
        dialog = QDialog(self)
        dialog.setWindowTitle(f"编辑计划 {plan.get('plan_name', '')}")
        layout = QFormLayout(dialog)
        # 显示患者信息（不可编辑）
        patient_name = plan.get('patient_name', '未知患者')
        patient_label = QLabel(patient_name)
        layout.addRow("患者:", patient_label)
        # 可编辑字段
        self.edit_plan_name = QLineEdit(plan.get('plan_name', ''))
        # 日期处理
        start_date = plan.get('start_date', '')
        end_date = plan.get('end_date', '')
        try:
            if isinstance(start_date, str):
                self.edit_start_date = QDateEdit(QDate.fromString(start_date, "yyyy-MM-dd"))
            else:  # date对象
                self.edit_start_date = QDateEdit(QDate(start_date.year, start_date.month, start_date.day))
        except:
            self.edit_start_date = QDateEdit(QDate.currentDate())
        try:
            if isinstance(end_date, str):
                self.edit_end_date = QDateEdit(QDate.fromString(end_date, "yyyy-MM-dd"))
            else:  # date对象
                self.edit_end_date = QDateEdit(QDate(end_date.year, end_date.month, end_date.day))
        except:
            self.edit_end_date = QDateEdit(QDate.currentDate())
        self.edit_start_date.setCalendarPopup(True)
        self.edit_end_date.setCalendarPopup(True)
        # 状态选择（匹配数据库ENUM）
        self.edit_status_combo = QComboBox()
        self.edit_status_combo.addItems(["active", "completed", "paused"])
        current_status = plan.get('status', 'active')
        index = self.edit_status_combo.findText(current_status)
        if index >= 0:
            self.edit_status_combo.setCurrentIndex(index)
        # 频率选择（匹配数据库ENUM）
        self.edit_frequency_combo = QComboBox()
        self.edit_frequency_combo.addItems(["daily", "weekly", "biweekly"])
        current_frequency = plan.get('frequency', 'daily')
        index = self.edit_frequency_combo.findText(current_frequency)
        if index >= 0:
            self.edit_frequency_combo.setCurrentIndex(index)
        layout.addRow("计划名称:", self.edit_plan_name)
        layout.addRow("开始日期:", self.edit_start_date)
        layout.addRow("结束日期:", self.edit_end_date)
        layout.addRow("训练频率:", self.edit_frequency_combo)
        layout.addRow("状态:", self.edit_status_combo)
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addRow(buttons)
        if dialog.exec_() == QDialog.Accepted:
            updated_data = {
                'plan_id': plan['plan_id'],
                'plan_name': self.edit_plan_name.text(),
                'start_date': self.edit_start_date.date().toString("yyyy-MM-dd"),
                'end_date': self.edit_end_date.date().toString("yyyy-MM-dd"),
                'frequency': self.edit_frequency_combo.currentText(),
                'status': self.edit_status_combo.currentText()
            }
            success, message = self.auth_manager.update_rehab_plan(updated_data)
            if success:
                QMessageBox.information(self, "成功", message)
                self.load_data()
            else:
                QMessageBox.warning(self, "失败", message)

    def confirm_delete_plan(self, plan_id):
        """确认删除康复计划"""
        reply = QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除康复计划 {plan_id} 吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No,  # 统一使用 QMessageBox
            QMessageBox.No
        )
        if reply == QMessageBox.Yes:
            try:
                success, message = self.auth_manager.delete_rehab_plan(
                    self.user_info['user_id'],
                    plan_id
                )
                if success:
                    QMessageBox.information(self, "成功", message)
                    self.load_data()
                else:
                    QMessageBox.warning(self, "失败", message)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败: {str(e)}")

    def logout(self):
        """退出登录"""
        self.close()